package com.dys.listener;

import javax.servlet.*;

/**
 * @Author: 疾风
 * @ClassName: MyRequestListener
 * @Description: Request监听器
 * @CreateDate: 2024/09/25
 * @Version: v1.0.0
 */
public class MyRequestListener implements ServletRequestListener, ServletRequestAttributeListener {
    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        // 监听HttpServletRequest对象的创建并初始化 项目中任何一个Request对象的创建并初始化都会触发该方法的执行
        ServletRequest servletRequest = sre.getServletRequest();
        System.out.println("Request对象初始化，其中HashCode码为："+servletRequest.hashCode());
        System.out.println("MyRequestListener 重写的requestInitialized()方法......");
    }

    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        // 监听HttpServletRequest对象的销毁  项目中任何一个Request对象的销毁都会触发该方法的执行
        ServletRequest servletRequest = sre.getServletRequest();
        System.out.println("Request对象被销毁了，其中HashCode码为："+servletRequest.hashCode());
        System.out.println("MyRequestListener 重写的 requestDestroyed()方法......");
    }

    @Override
    public void attributeAdded(ServletRequestAttributeEvent srae) {
        // 任何一个Request对象中调用 setAttribute方法增加了数据都会触发该方法
        ServletRequest servletRequest = srae.getServletRequest();
        String name = srae.getName();
        Object value = srae.getValue();
        System.out.println("Request对象初始化, 其中HashCode码为："+servletRequest.hashCode()+",往Request域中添加了数据："+name+"="+value);
    }

    @Override
    public void attributeRemoved(ServletRequestAttributeEvent srae) {
        // 任何一个Request对象中调用 setAttribute方法增加了数据都会触发该方法
        ServletRequest servletRequest = srae.getServletRequest();
        String name = srae.getName();
        Object value = srae.getValue();
        System.out.println("Request对象初始化, 其中HashCode码为："+servletRequest.hashCode()+",往Request域中移除了数据："+name+"="+value);
    }

    @Override
    public void attributeReplaced(ServletRequestAttributeEvent srae) {
        // 任何一个Request对象中调用 setAttribute方法增加了数据都会触发该方法
        ServletRequest servletRequest = srae.getServletRequest();
        String name = srae.getName();
        Object value = srae.getValue(); Object newValue=servletRequest.getAttribute(name);
        System.out.println("Request对象初始化, 其中HashCode码为："+servletRequest.hashCode()+"往Request域中修改了数据，将"+name+"="+value+"设置为:"+newValue);
    }
}
